import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/model/notice.dart';
import 'package:line_awesome_icons/line_awesome_icons.dart';

import 'notice_detail_view.dart';

class NoticeItemWidget extends StatefulWidget {
  final Notice notice;
  final Function(String) onRemove;
  final SlidableController controller;

  const NoticeItemWidget({
    Key key,
    @required this.notice,
    @required this.onRemove,
    @required this.controller,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _NoticeItemWidgetState();
  }
}

class _NoticeItemWidgetState extends State<NoticeItemWidget> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Slidable(
        controller: widget.controller,
        actionPane: SlidableScrollActionPane(),
        child: itemBody(),
        secondaryActions: [
          IconSlideAction(
            caption: '删除',
            color: widget.notice.read ? Colors.red : Colors.black12,
            icon: Icons.delete,
            onTap: () {
              if (!widget.notice.read) return;
              widget.onRemove(widget.notice.id);
            },
          ),
        ],
      ),
      onTap: () async {
        await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (cxt) => NoticeDetailView(noticeId: widget.notice.id),
          ),
        );
        setState(() {
          widget.notice.read = true;
        });
      },
    );
  }

  Widget itemBody() {
    var format = new DateFormat('yyyy-MM-dd');
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(bottom: 1),
      child: ListTile(
        leading: Icon(
          LineAwesomeIcons.bell,
          color: Colors.black54,
          size: 24,
        ),
        title: Text(widget.notice.title),
        subtitle: Text(
          format.format(widget.notice.createTime),
          style: TextStyle(fontSize: 12),
        ),
        trailing: Text(
          widget.notice.read ? '已读' : '未读',
          style: TextStyle(
            color: widget.notice.read ? Colors.black54 : Colors.red,
            fontSize: 13,
          ),
        ),
      ),
    );
  }
}
